package com.test.multithread;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.util.concurrent.CountDownLatch;

/**
 * Created by jl on 2016/8/7.
 */
public class Demo {
    public static void main(String[] args) throws FileNotFoundException, InterruptedException {
        final int DOWN_THREAD_NUM = 5;//起5个线程去读取指定文件
        CountDownLatch latch = new CountDownLatch(DOWN_THREAD_NUM);
        RandomAccessFile[] outArr = new RandomAccessFile[DOWN_THREAD_NUM];
        File file = new File("test.txt");

        long t1 = System.currentTimeMillis();
        long fileLen = file.length();
        System.out.println("文件总大小" + fileLen + "byte");
        long numPerThread = fileLen / DOWN_THREAD_NUM;
        System.out.println("每个线程读的字节数：" + numPerThread);
        //剩余的余数
        long left = fileLen % DOWN_THREAD_NUM;
        //创建线程并运行
        for (int i =0;i<DOWN_THREAD_NUM;i++) {
            outArr[i] = new RandomAccessFile(file, "rw");
            if (i == DOWN_THREAD_NUM - 1) {
                //最后一个线程读取指定numPerThred+left个字节
                System.out.println("最后一个线程读取从" + i * numPerThread + "到" + ((i + 1) * numPerThread + left) + "的位置");
                new ReadThread(i * numPerThread, (i + 1) * numPerThread + left, outArr[i], "nothing", latch).start();
            } else {
                System.out.println("第" + i + "个线程读取从" + i * numPerThread + "到" + ((i + 1) * numPerThread) + "的位置");
                new ReadThread(i * numPerThread, (i + 1) * numPerThread, outArr[i], "nothing", latch).start();
            }

        }
        //确认所有线程任务完成，开始执行主线程的操作
        latch.await();
        System.out.println("耗时：" + (System.currentTimeMillis() - t1) + "ms");
    }
}
